package com.zhz.lib.cms.manage.libnews;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.zhz.lib.cms.domain.libnews.Libnews;
import com.zhz.lib.cms.domain.type.Sortmap;
import com.zhz.lib.cms.manage.BaseActionWithApprove;
import com.zhz.lib.cms.utils.zhz.ZhzSecurityUtil;
import com.zhz.lib.cms.utils.zhz.ZhzSortMapUtil;
import com.zhz.lib.cms.vo.libnews.LibnewsVO;
import com.zhz.project.common.util.alibaba.StringUtil;
import com.zhz.project.common.util.hibernate.BaseDAO;
import com.zhz.project.common.util.zhzutil.ZhzDateUtil;
import com.zhz.project.common.util.zhzutil.ZhzHttpRequestUtil;
import com.zhz.project.common.util.zhzutil.ZhzStringUtil;

public class libnewsAction extends BaseActionWithApprove {
    private static String       TABLE  = "Libnews";
    private static String       KEY    = "libnewsId";
    private static String       LIST   = "libnewslist";

    private static final int    length = 30;
    private static Logger       logger = Logger.getLogger(libnewsAction.class);

    // 馆内信息来源系列downlist ID
    private Integer             libnewsfromfatherid;
    // 馆内信息类别系列的 downlist ID
    private Integer             libnewstypefatherid;
    // 事务模板
    private TransactionTemplate transactionTemplate;

    /**
     * 不给参数，默认执行此处
     */
    @Override
    public ActionForward unspecified(ActionMapping mapping, ActionForm form,
                                     HttpServletRequest request, HttpServletResponse response)
                                                                                              throws Exception {
        return libnewslist(mapping, form, request, response);
    }

    /**
     * 显示馆内信息列表
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @SuppressWarnings("unchecked")
    public ActionForward libnewslist(ActionMapping mapping, ActionForm form,
                                     HttpServletRequest request, HttpServletResponse response)
                                                                                              throws Exception {

        // ////////////////////////////////////////////////////////////////////////
        // 获取新闻来源
        String libnewsfrom = ZhzHttpRequestUtil.getParameters(request, "libnewsfrom");
        // 获取新闻类型
        String sortType = ZhzHttpRequestUtil.getParameters(request, "sortType");

        request.setAttribute("libnewsfrom", libnewsfrom);
        request.setAttribute("sortType", sortType);

        // 上面是提取参数并输出到页面中
        // ////////////////////////////////////////////////////////////////////////

        String whereStatement = BaseDAO.WHERE;
        StringBuffer fanyeHref = new StringBuffer();
        fanyeHref.append("libnewsManage.do?method=libnewslist");

        // 根据新闻来源进行查询
        if (StringUtil.isNotBlank(sortType)) {
            whereStatement += "and sortType =" + sortType;
            fanyeHref.append("&sortType=");
            fanyeHref.append(sortType);
        }
        // 根据新闻类型进行查询
        if (StringUtil.isNotBlank(libnewsfrom)) {
            whereStatement += " and libnewsfrom =" + libnewsfrom;
            fanyeHref.append("&libnewsfrom=");
            fanyeHref.append(libnewsfrom);
        }

        List<Libnews> libnewslist = getListWithFanyeHref(request, TABLE, whereStatement
                                                                         + BaseDAO.WHERE_DELETE,
            " order by " + KEY + " DESC", LIST, fanyeHref);

        List<LibnewsVO> newsVOlist = new ArrayList<LibnewsVO>();

        if (libnewslist != null && libnewslist.size() > 0) {
            for (Libnews libnews : libnewslist) {
                newsVOlist.add(changeToVo(libnews, true));
            }
        }
        request.setAttribute(LIST, newsVOlist);

        return mapping.findForward("libnews-list");
    }

    /**
     * 添加馆内信息
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward libnewsadd(ActionMapping mapping, ActionForm form,
                                    HttpServletRequest request, HttpServletResponse response) {
        request.setAttribute("writer", ZhzSecurityUtil.getOperatorName());

        // 列出馆内信息来源
        request.setAttribute("libnewsfrominfolist", ZhzSortMapUtil.getChildSortMapList(
            this.libnewsfromfatherid, baseDao));
        // 列出馆内信息类型
        request.setAttribute("libnewstypeinfolist", ZhzSortMapUtil.getChildSortMapList(
            this.libnewstypefatherid, baseDao));

        return mapping.findForward("libnews-add");

    }

    /**
     * 提交馆内信息
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward libnewssave(ActionMapping mapping, ActionForm form,
                                     HttpServletRequest request, HttpServletResponse response) {

        // 获取馆内信息的标题
        String title = ZhzHttpRequestUtil.getParameters(request, "title");
        // 获取馆内信息的主内容
        String libnewscontent = ZhzHttpRequestUtil.getParameters(request, "libnewscontent");
        // 获取馆内信息的来源
        String libnewsfrom = ZhzHttpRequestUtil.getParameters(request, "libnewsfrom");
        // 获取馆内信息的类型
        String libnewstype = ZhzHttpRequestUtil.getParameters(request, "libnewstype");

        Libnews libnews = new Libnews();

        libnews.setTitle(title);
        libnews.setContent(libnewscontent);
        libnews.setWriter(ZhzSecurityUtil.getOperatorName());
        libnews.setLibnewsfrom(libnewsfrom);
        libnews.setKeyword(null);
        libnews.setSortType(libnewstype);
        String pubdate = request.getParameter("pubdate");
        if (StringUtil.isNotBlank(pubdate)) {
            libnews.setPubDate(ZhzDateUtil.getYYYYMDDDate(request.getParameter("pubdate")));
        } else {
            libnews.setPubDate(new Date());
        }
        libnews.setHit(0);
        libnews.setAproveState(0);
        libnews.setAproveTime(null);
        libnews.setEditor(ZhzSecurityUtil.getOperatorName());
        libnews.setEditorTime(new Date());
        libnews.setIfDelete(0);

        request.setAttribute("add", true);

        boolean x = baseDao.save(libnews);

        if (x) {
            request.setAttribute("add", "add");
            request.setAttribute("addresult", "addresult");
        }

        return mapping.findForward("libnews-result");
    }

    /**
     * 编辑馆内信息
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward libnewsedit(ActionMapping mapping, ActionForm form,
                                     HttpServletRequest request, HttpServletResponse response) {

        String libnewsid = ZhzHttpRequestUtil.getParameters(request, "libnewsid");

        // 获取馆内信息
        Libnews libnews = (Libnews) baseDao.findOneObject("Libnews", "libnewsId", libnewsid);
        request.setAttribute("libnews", libnews);

        Sortmap libnewsfrom = (Sortmap) baseDao.findOneObject("Sortmap", "sortMapId", libnews
            .getLibnewsfrom());
        request.setAttribute("libnewsfrom", libnewsfrom);

        Sortmap sortType = (Sortmap) baseDao.findOneObject("Sortmap", "sortMapId", libnews
            .getSortType());
        request.setAttribute("sortType", sortType);

        // 列出馆内信息来源
        request.setAttribute("libnewsfrominfolist", ZhzSortMapUtil.getChildSortMapList(
            this.libnewsfromfatherid, baseDao));
        // 列出馆内信息类型
        request.setAttribute("libnewstypeinfolist", ZhzSortMapUtil.getChildSortMapList(
            this.libnewstypefatherid, baseDao));

        return mapping.findForward("libnewsedit-form");
    }

    /**
     * 编辑馆内信息提交
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward libnewseditsave(ActionMapping mapping, ActionForm form,
                                         HttpServletRequest request, HttpServletResponse response) {

        String libnewsid = ZhzHttpRequestUtil.getParameters(request, "libnewsid");

        // 获取馆内信息的标题
        String title = ZhzHttpRequestUtil.getParameters(request, "title");
        // 获取馆内信息的主内容
        String libnewscontent = ZhzHttpRequestUtil.getParameters(request, "libnewscontent");
        // 获取馆内信息的来源
        String libnewsfrom = ZhzHttpRequestUtil.getParameters(request, "libnewsfrom");
        // 获取馆内信息的类型
        String libnewstype = ZhzHttpRequestUtil.getParameters(request, "libnewstype");

        Libnews libnews = (Libnews) baseDao.findOneObject("Libnews", "libnewsId", libnewsid);

        libnews.setTitle(title);
        libnews.setContent(libnewscontent);
        libnews.setLibnewsfrom(libnewsfrom);
        libnews.setSortType(libnewstype);
        String pubdate = request.getParameter("pubdate");
        if (StringUtil.isNotBlank(pubdate)) {
            libnews.setPubDate(ZhzDateUtil.getYYYYMDDDate(request.getParameter("pubdate")));
        } else {
            libnews.setPubDate(new Date());
        }
        libnews.setEditor(ZhzSecurityUtil.getOperatorName());
        libnews.setEditorTime(new Date());

        request.setAttribute("edit", true);

        boolean x = baseDao.update(libnews);
        if (x) {
            request.setAttribute("edit", "edit");
            request.setAttribute("editresult", "editresult");
        }

        return mapping.findForward("libnews-result");

    }

    /**
     * 删除馆内信息
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward libnewsdel(ActionMapping mapping, ActionForm form,
                                    HttpServletRequest request, HttpServletResponse response)
                                                                                             throws Exception {
        boolean delResult = false;
        String libnewsidString = ZhzHttpRequestUtil.getParameters(request, "libnewsid");

        if (ZhzStringUtil.isNotNull(libnewsidString)) {
            Libnews libnews = (Libnews) baseDao.findOneObject("Libnews", "libnewsId",
                libnewsidString);
            // 设为删除
            libnews.setIfDelete(1);
            libnews.setEditor(ZhzSecurityUtil.getOperatorName());
            libnews.setEditorTime(new Date());

            delResult = baseDao.update(libnews);
        }

        if (delResult) {
            request.setAttribute("del", "del");
            request.setAttribute("delResult", "delResult");
        }
        return mapping.findForward("libnews-result");
    }

    /**
     * 通过ajax请求，获取馆内信息列表
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward libnewsContent(ActionMapping mapping, ActionForm form,
                                        HttpServletRequest request, HttpServletResponse response)
                                                                                                 throws Exception {
        String libnewsid = ZhzHttpRequestUtil.getParameters(request, "libnewsid");
        if (ZhzStringUtil.isNotNull(libnewsid)) {
            Libnews libnews = (Libnews) baseDao.findOneObject("Libnews", "libnewsId", libnewsid);
            request.setAttribute("libnews", changeToVo(libnews, false));
        } else {
            return null;
        }

        return mapping.findForward("libnews-content");
    }

    /**
     * 审核馆内信息
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public ActionForward libnewsApprove(ActionMapping mapping, ActionForm form,
                                        HttpServletRequest request, HttpServletResponse response)
                                                                                                 throws Exception {

        // 获取所有的参数
        Enumeration allParameter = request.getParameterNames();

        // 0 未审核 1 通过 2 不通过
        String aproveState = ZhzHttpRequestUtil.getParameters(request, "approveState");

        final int apoveStateInt = Integer.parseInt(aproveState);

        // 获取选择的所有待审核的模块
        final Set<String> newsIdSet = new HashSet<String>();

        String name = null;
        while (allParameter.hasMoreElements()) {
            name = (String) allParameter.nextElement();
            if (ZhzStringUtil.isNotNull(name) && StringUtil.contains(name, "checkbox")) {
                // 将含有值的checkbox，赋值
                newsIdSet.add(request.getParameter(name));
            }
        }
        // 在事务中进行
        boolean approveResult = (Boolean) transactionTemplate.execute(new TransactionCallback() {

            public Object doInTransaction(TransactionStatus status) {

                try {
                    Iterator<String> it = newsIdSet.iterator();
                    while (it.hasNext()) {
                        String libnewsId = it.next();
                        Libnews libnews = (Libnews) baseDao.findOneObject("Libnews", "libnewsId",
                            libnewsId);
                        libnews.setAproveState(apoveStateInt);
                        libnews.setAproveTime(Calendar.getInstance().getTime());
                        libnews.setEditor(ZhzSecurityUtil.getOperatorName());
                        libnews.setEditorTime(new Date());

                        baseDao.update(libnews);
                    }
                } catch (Exception e) {
                    status.setRollbackOnly();
                    return false;
                }
                return true;
            }
        });

        if (approveResult) {
            request.setAttribute("app", "app");
            request.setAttribute("approveResult", "approveResult");
        }

        return mapping.findForward("libnews-result");
    }

    /**
     * 将news转换为页面需要的数据
     * 
     * @param news
     */
    private LibnewsVO changeToVo(Libnews libnews, boolean needCut) {
        LibnewsVO libnewsVO = new LibnewsVO();
        BeanUtils.copyProperties(libnews, libnewsVO);

        Sortmap smp = (Sortmap) baseDao.findOneObject("Sortmap", "sortMapId", libnews
            .getLibnewsfrom());
        if (smp != null)
            libnewsVO.setLibnewsfromString(smp.getValue());
        smp = (Sortmap) baseDao.findOneObject("Sortmap", "sortMapId", libnews.getSortType());
        if (smp != null)
            libnewsVO.setSortTypeString(smp.getValue());
        if (needCut && StringUtil.isNotBlank(libnewsVO.getTitle()))
            if (libnewsVO.getTitle().getBytes().length > length)
                libnewsVO.setTitle(ZhzStringUtil.subStringWithDot(libnewsVO.getTitle(), length));

        return libnewsVO;
    }

    public void setLibnewsfromfatherid(Integer libnewsfromfatherid) {
        this.libnewsfromfatherid = libnewsfromfatherid;
    }

    public void setLibnewstypefatherid(Integer libnewstypefatherid) {
        this.libnewstypefatherid = libnewstypefatherid;
    }

    @Override
    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }
}